(function () {
var system = require('system');
var realPath = 'script/';
	var fs = require('fs');
	var config = {
        // define the location of js files
        JQUERY: realPath+'jquery.min.js',
        ECHARTS: realPath+ 'echarts.min.js',
		CHINA: realPath+ 'china.js',
		RESET: realPath+ 'reset.css',
		
        // default container width and height
        DEFAULT_WIDTH: '600',
        DEFAULT_HEIGHT: '700'
       }, parseParams, render, usage,pick;
 
	    parseParams = function () {
        var map = {}, i, key;
        if (system.args.length < 2) {
            usage();
            phantom.exit();
        }
        for (i = 0; i < system.args.length; i += 1) {
            if (system.args[i].charAt(0) === '-') {
                key = system.args[i].substr(1, i.length);
                if (key === 'infile') {
                    // get string from file
                    // force translate the key from infile to options.
                    key = 'options';
                    try {
                        map[key] = fs.read(system.args[i + 1]).replace(/^\s+/, '');
                    } catch (e) {
                        console.log('Error: cannot find file, ' + system.args[i + 1]);
                        phantom.exit();
                    }
                } else {
                    map[key] = system.args[i + 1];
                }
            }
        }
        return map;
    };

    pick = function () {
        var args = arguments, i, arg, length = args.length;
        for (i = 0; i < length; i += 1) {
            arg = args[i];
            if (arg !== undefined && arg !== null && arg !== 'null' && arg != '0') {
                return arg;
            }
        }
    };



    // get the args
    var params = parseParams();
	var render = function (params) {

		var page = require('webpage').create(), createChart;


		createChart = function (inputOption, width, height) {
            var counter = 0;
            function decrementImgCounter() {
                counter -= 1;
                if (counter < 1) {
                    console.log(messages.imagesLoaded);
                }
            }

            function loadScript(varStr, codeStr) {
                var script = $('<script>').attr('type', 'text/javascript');
                script.html('var ' + varStr + ' = ' + codeStr);
                document.getElementsByTagName("head")[0].appendChild(script[0]);
                if (window[varStr] !== undefined) {
                    console.log('Echarts.' + varStr + ' has been parsed');
                }
            }

            function loadImages() {
                var images = $('image'), i, img;
                if (images.length > 0) {
                    counter = images.length;
                    for (i = 0; i < images.length; i += 1) {
                        img = new Image();
                        img.onload = img.onerror = decrementImgCounter;
                        img.src = images[i].getAttribute('href');
                    }
                } else {
                    console.log('The images have been loaded');
                }
            }
            // load opitons
            if (inputOption != 'undefined') {
                // parse the options
                loadScript('options', inputOption);
                // disable the animation
                options.animation = false;
            }

            // we render the image, so we need set background to white.
            $(document.body).css('backgroundColor', 'white');
				var container = $("<div>").appendTo(document.body);
				container.attr('id', 'container');
				container.css({
					width: width,
					height: height
				});
				// render the chart
				var myChart = echarts.init(container[0]);
				myChart.setOption(options);
				// load images
				loadImages();
            
        	};	

			page.open("about:blank", function (status) {
			 
				// 注入依赖js包
				var hasJquery =page.injectJs(config.JQUERY);
				var hasEchart = page.injectJs(config.ECHARTS);
				page.injectJs(config.CHINA);
		
				// 检查js是否引用成功
				if (!hasJquery && !hasEchart) {
					console.log("Could not found " + config.JQUERY + " or " + config.ECHARTS);
				}

				var width = pick(params.width, config.DEFAULT_WIDTH);
				var height = pick(params.height, config.DEFAULT_HEIGHT);
		
				// create the chart
				page.evaluate(createChart, params.options, width, height);

				// render the image
				page.render(params.outfile);

				phantom.exit();
		})
	}
	render(params);
}());	
